package com.itfreer.gis.server;

import io.minio.MinioClient;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.Item;
import io.minio.policy.PolicyType;
import org.junit.Test;
import org.xmlpull.v1.XmlPullParserException;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;

/**
 * minio指定桶下的目录的文件查找
 */
public class FindList {

    private String imageBucket = "image";

    private int count = 0;

    @Test
    public void test() throws IOException, XmlPullParserException, NoSuchAlgorithmException, RegionConflictException, InvalidObjectPrefixException, InvalidKeyException, InvalidPortException, ErrorResponseException, NoResponseException, InvalidBucketNameException, InsufficientDataException, InvalidEndpointException, InternalException {
        MinioClient minioClient = getMinioClient();

        Iterable<Result<Item>> results = minioClient.listObjects(imageBucket, "CD/");
        Iterator<Result<Item>> iterator = results.iterator();
        while (iterator.hasNext()) {
            Result<Item> result = (Result<Item>) iterator.next();
            Map<String, Object> map = result.get();

            for (String s : map.keySet()) {
                Object a = map.get(s);
                if (s.equals("Key")) {
                    System.out.println(a);
                    count ++;
                }
            }
        }

        System.out.println(count);
    }


    /**
     * 获取Minio链接
     *
     * @return
     * @throws InvalidPortException
     * @throws InvalidEndpointException
     * @throws IOException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InsufficientDataException
     * @throws InternalException
     * @throws NoResponseException
     * @throws InvalidBucketNameException
     * @throws XmlPullParserException
     * @throws ErrorResponseException
     * @throws RegionConflictException
     * @throws InvalidObjectPrefixException
     */
    public MinioClient getMinioClient() throws InvalidPortException, InvalidEndpointException, IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException, RegionConflictException, InvalidObjectPrefixException {
        // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        MinioClient minioClient = new MinioClient("http://47.106.79.19:9000", "minio", "123!@#qweQWE@ITFREER");

        // 检查存储桶是否已经存在
        boolean isExist = minioClient.bucketExists(imageBucket);
        if (!isExist) {
            // 创建一个名为asiatrip的存储桶，用于存储照片文件。
            minioClient.makeBucket(imageBucket);
            minioClient.setBucketPolicy(imageBucket, "*", PolicyType.READ_WRITE);
        }
        return minioClient;
    }


}

